// auth.js - JWT认证管理
class AuthManagerClass {
    constructor() {
        this.baseUrl = '/ercms';
        this.token = localStorage.getItem('jwt_token');
        this.userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
        this.init();
    }

    init() {
        console.log('AuthManager 初始化开始...');
        console.log('  从localStorage加载token:', !!this.token);
        console.log('  从localStorage加载userInfo:', !!this.userInfo);
        console.log('  token值:', this.token ? this.token.substring(0, 20) + '...' : 'null');
        console.log('  userInfo值:', this.userInfo);
        
        if (this.token) {
            this.setupRequestInterceptor();
            console.log('  设置请求拦截器完成');
        } else {
            console.log('  未找到token，跳过请求拦截器设置');
        }
        
        console.log('AuthManager 初始化完成');
    }

    // 检查认证状态
    checkAuthStatus() {
        console.log('checkAuthStatus 被调用');
        console.log('  当前token:', !!this.token);
        console.log('  当前userInfo:', !!this.userInfo);
        
        // 如果token存在但userInfo不存在，尝试从localStorage重新加载
        if (this.token && !this.userInfo) {
            console.log('  token存在但userInfo不存在，尝试重新加载');
            this.userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
            console.log('  重新加载后的userInfo:', this.userInfo);
        }
        
        // 恢复认证检查
        if (!this.isAuthenticated()) {
            console.log('  用户未认证，重定向到登录页');
            this.redirectToLogin();
            return false;
        }
        
        console.log('checkAuthStatus 完成，用户已认证');
        return true;
    }

    // 验证token
    async verifyToken() {
        try {
            const response = await fetch(`${this.baseUrl}/api/auth/verify`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('Token验证失败');
            }

            const data = await response.json();
            if (!data.success) {
                throw new Error(data.message || 'Token无效');
            }

            // 更新用户信息
            this.userInfo = data.user;
            localStorage.setItem('user_info', JSON.stringify(data.user));
            
            return data;
        } catch (error) {
            console.error('Token验证失败:', error);
            throw error;
        }
    }

    // 登录
    async login(username, password) {
        try {
            // 登录时清除旧的认证信息
            this.clearAuth();
            
            const response = await fetch(`${this.baseUrl}/api/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            const data = await response.json();
            
            if (data.success) {
                this.token = data.token;
                this.userInfo = data.user;
                
                localStorage.setItem('jwt_token', data.token);
                localStorage.setItem('user_info', JSON.stringify(data.user));
                
                // 设置请求拦截器
                this.setupRequestInterceptor();
                
                return data;
            } else {
                throw new Error(data.message || '登录失败');
            }
        } catch (error) {
            console.error('登录失败:', error);
            throw error;
        }
    }

    // 注册
    async register(userData) {
        try {
            const response = await fetch(`${this.baseUrl}/api/auth/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            const data = await response.json();
            
            if (data.success) {
                return data;
            } else {
                throw new Error(data.message || '注册失败');
            }
        } catch (error) {
            console.error('注册失败:', error);
            throw error;
        }
    }

    // 刷新token
    async refreshToken() {
        try {
            const response = await fetch(`${this.baseUrl}/api/auth/refresh`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.token}`,
                    'Content-Type': 'application/json'
                }
            });

            const data = await response.json();
            
            if (data.success) {
                this.token = data.token;
                localStorage.setItem('jwt_token', data.token);
                return data.token;
            } else {
                throw new Error(data.message || 'Token刷新失败');
            }
        } catch (error) {
            console.error('Token刷新失败:', error);
            throw error;
        }
    }

    // 登出
    async logout() {
        try {
            console.log('开始退出登录流程');
            
            // 调用后端退出登录API
            if (this.token) {
                try {
                    const response = await fetch(`${this.baseUrl}/api/auth/logout`, {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${this.token}`,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        console.log('后端退出登录成功:', data.message);
                    } else {
                        console.warn('后端退出登录失败，但继续清除本地数据');
                    }
                } catch (error) {
                    console.warn('调用退出登录API失败，但继续清除本地数据:', error);
                }
            }
            
            // 清除本地认证信息
            this.clearAuth();
            
            // 显示退出成功消息
            this.showLogoutMessage();
            
            // 重定向到登录页
            setTimeout(() => {
                this.redirectToLogin();
            }, 1000);
            
        } catch (error) {
            console.error('退出登录失败:', error);
            // 即使出错也要清除本地数据
            this.clearAuth();
            this.redirectToLogin();
        }
    }

    // 显示退出成功消息
    showLogoutMessage() {
        // 创建一个临时的消息提示
        const messageDiv = document.createElement('div');
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #28a745;
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 9999;
            font-size: 14px;
        `;
        messageDiv.textContent = '退出登录成功，正在跳转...';
        document.body.appendChild(messageDiv);
        
        // 3秒后移除消息
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 3000);
    }

    // 清除认证信息
    clearAuth() {
        this.token = null;
        this.userInfo = null;
        localStorage.removeItem('jwt_token');
        localStorage.removeItem('user_info');
    }

    // 重定向到登录页
    redirectToLogin() {
        console.log('准备重定向到登录页，当前路径:', window.location.pathname);
        if (window.location.pathname !== '/ercms/login') {
            window.location.href = '/ercms/login';
        }
    }

    // 设置请求拦截器
    setupRequestInterceptor() {
        console.log('设置请求拦截器');
        
        // 重写fetch方法以自动添加token
        const originalFetch = window.fetch;
        window.fetch = async (url, options = {}) => {
            // 只对API请求添加token，但排除登录和注册请求
            if (url.includes('/api/') && this.token && 
                !url.includes('/api/auth/login') && 
                !url.includes('/api/auth/register')) {
                options.headers = {
                    ...options.headers,
                    'Authorization': `Bearer ${this.token}`
                };
            }

            try {
                const response = await originalFetch(url, options);
                
                // 处理401错误
                if (response.status === 401) {
                    // 尝试刷新token
                    try {
                        await this.refreshToken();
                        // 重新发送请求
                        options.headers = {
                            ...options.headers,
                            'Authorization': `Bearer ${this.token}`
                        };
                        return await originalFetch(url, options);
                    } catch (refreshError) {
                        // 刷新失败，清除认证信息并重定向
                        this.clearAuth();
                        this.redirectToLogin();
                        throw new Error('认证失败，请重新登录');
                    }
                }
                
                return response;
            } catch (error) {
                throw error;
            }
        };
        
        console.log('请求拦截器设置完成');
    }

    // 获取用户信息
    getUserInfo() {
        // 如果userInfo不存在但token存在，尝试重新加载
        if (!this.userInfo && this.token) {
            console.log('getUserInfo: userInfo不存在，尝试重新加载');
            this.userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
            console.log('getUserInfo: 重新加载后的userInfo:', this.userInfo);
        }
        return this.userInfo;
    }

    // 获取token
    getToken() {
        return this.token;
    }

    // 检查是否有权限
    hasRole(role) {
        return this.userInfo && this.userInfo.role === role;
    }

    // 检查是否有任意权限
    hasAnyRole(roles) {
        return this.userInfo && roles.includes(this.userInfo.role);
    }

    // 检查是否已登录
    isAuthenticated() {
        console.log('isAuthenticated 被调用:');
        console.log('  token存在:', !!this.token);
        console.log('  userInfo存在:', !!this.userInfo);
        console.log('  token值:', this.token ? this.token.substring(0, 20) + '...' : 'null');
        console.log('  userInfo值:', this.userInfo);
        
        // 如果token存在但userInfo不存在，尝试从localStorage重新加载
        if (this.token && !this.userInfo) {
            console.log('  token存在但userInfo不存在，尝试重新加载');
            this.userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
            console.log('  重新加载后的userInfo:', this.userInfo);
        }
        
        // 只要有token就认为已认证，userInfo可以在后续加载
        const authenticated = !!this.token;
        console.log('  认证结果:', authenticated);
        return authenticated;
    }

    // 获取认证头
    getAuthHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };
        
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        
        return headers;
    }
}

// 创建全局认证管理器实例
const authManagerInstance = new AuthManagerClass();

// 暴露为全局对象
window.authManager = authManagerInstance;
window.AuthManager = authManagerInstance;

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AuthManagerClass;
} 